package hai.com.android_test.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import hai.com.android_test.R;
import hai.com.android_test.widget.MyWebChromeClient;
import hai.com.android_test.widget.MyWebViewClient;

public class WebViewActivity extends AppCompatActivity {
    ValueCallback<Uri[]> valueCallback;
    ValueCallback<Uri> uploadFile;
    public static final int CODE_CAMERA = 0X100;
    public static final int CODE_CHOOSER = 0X101;
    private static final String TAG = "WebViewActivity";
    @BindView(R.id.webview)
    WebView webview;

    String uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);
        afterBind();
        uri = getIntent().getStringExtra("uri");
        load(uri);
    }

    void load(String uri) {
        if (!TextUtils.isEmpty(uri)) {
            this.uri = uri;
            Log.e(TAG, "打开网页:uri=" + uri);
            syncCookie(uri);
            webview.loadUrl(uri);
        }
    }


    private void afterBind() {
        CookieManager instance = CookieManager.getInstance();
        instance.setAcceptCookie(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            instance.setAcceptThirdPartyCookies(webview, true);
        }
        webview.setWebViewClient(new MyWebViewClient());
        webview.setWebChromeClient(new MyWebChromeClient(this));
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setTextSize(WebSettings.TextSize.NORMAL);//设置字体不随系统字体大小变化
        settings.setDomStorageEnabled(true);//解决浏览器有些页面跳转失败问题
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        int densityDpi = getResources().getDisplayMetrics().densityDpi;
        WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.MEDIUM;
        switch (densityDpi) {
            case DisplayMetrics.DENSITY_LOW:
                zoomDensity = WebSettings.ZoomDensity.CLOSE;
                break;
            case DisplayMetrics.DENSITY_MEDIUM:
                zoomDensity = WebSettings.ZoomDensity.MEDIUM;
                break;
            case DisplayMetrics.DENSITY_HIGH:
                zoomDensity = WebSettings.ZoomDensity.FAR;
                break;
        }
        settings.setDefaultZoom(zoomDensity);
    }

    void syncCookie(String uri) {
        CookieManager instance = CookieManager.getInstance();
        java.net.CookieManager cookieManager = (java.net.CookieManager) java.net.CookieManager.getDefault();
        try {
            final Map<String, List<String>> cookiesMap = cookieManager.get(new URI(uri), new HashMap<String, List<String>>());
            if (cookiesMap != null && !cookiesMap.isEmpty()) {
                String key = (String) cookiesMap.keySet().toArray()[0];
                String value = cookiesMap.get(cookiesMap.keySet().toArray()[0]).get(0);
                instance.setCookie(new URI(uri).getHost(), value);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    instance.flush();
                } else {
                    CookieSyncManager.getInstance().sync();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_webview, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.refresh) {

            load(uri);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_CAMERA) {
            if (resultCode == RESULT_OK) {
                if (data.getData() == null) {
                    if (data.hasExtra("data")) {
                        Bitmap bitmap = data.getParcelableExtra("data");
                        Uri parse = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
                        setValueCallBack(parse);
                    } else setValueCallBack(null);
                } else setValueCallBack(data.getData());
            } else setValueCallBack(null);
        } else if (requestCode == CODE_CHOOSER) {
            if (resultCode == RESULT_OK) {
                setValueCallBack(data.getData());
            } else setValueCallBack(null);
        }
    }

    private void setValueCallBack(Uri uri) {
        if (uri == null) {
            if (valueCallback != null) valueCallback.onReceiveValue(null);
            if (uploadFile != null) uploadFile.onReceiveValue(null);
        } else {
            if (valueCallback != null) valueCallback.onReceiveValue(new Uri[]{uri});
            if (uploadFile != null) uploadFile.onReceiveValue(uri);
        }
    }

    public void setValueCallback(ValueCallback<Uri[]> valueCallback) {
        this.valueCallback = valueCallback;
    }

    public void setUploadFile(ValueCallback<Uri> uploadFile) {
        this.uploadFile = uploadFile;
    }
}
